package com.cd.university.common.lru;

import java.util.HashMap;
import java.util.Map;

/**
 * 这个是工厂类的简单工厂，也就是工厂的工厂，用来创建工厂类对象
 * @author 陈栋
 * @create 2021/12/11 16:51
 */
public class LRUMapFactory {
    private static final Map<String, LRUCacheFactory> cachedFactories = new HashMap<>();
    private static final int INIT_CAPACITY = 16;
    static {
        cachedFactories.put("linkMap",new LRULinkedHashMap(INIT_CAPACITY));
        cachedFactories.put("hashMap",new LRUHashMap(INIT_CAPACITY));
    }

    public static LRUCacheFactory getLRUCache(String type,int capacity) {
        checkIsExists(type);
        // 返回工厂类生成的对象
        return cachedFactories.get(type).createLRUCache(capacity);
    }

    public static LRUCacheFactory getLRUCache(String type) {
        checkIsExists(type);

        // 返回默认的工厂类生成的对象
        return cachedFactories.get(type);
    }

    /**
     * 检查类是否存在缓存中
     * @param type 类型
     */
    private static void checkIsExists(String type) {
        // 如果type为空或者map缓存中没有，那么抛出未找到类的异常
        if (type==null || type.isEmpty() || cachedFactories.get(type)==null) {
            try {
                throw new ClassNotFoundException("传入的type为空，或者该类不存在");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}
